package 代码记录.指定公司代码练习记录.华为_2024.分值100;

/**
 * @author zx
 * @create 2024-02-02 20:08
 * 看着有点难；主要是题目意思看的不够透彻；所以这个题不好做(人家的题解看懂就行)
 */
public class 字符串变换最小字符串_28 {
    /**
     * 后续看懂人家的题解就行，现在没看；暂时跳过
     */
    public static void main(String[] args) {
        try {
            String s = "abcdef";
            char[] charArray = s.toCharArray();
            int indexToSwap = findIndexToSwap(charArray);

            if (indexToSwap != -1) {
                swapAndPrint(charArray, indexToSwap);
            } else {
                System.out.println(s);
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    private static int findIndexToSwap(char[] arr) {
        int lastIndex = -1;
        for (int i = 0; i < arr.length - 1; i++) {
            char minChar = findMin(arr, i + 1);
            if (arr[i] > minChar) {
                int occurrences = countOccurrences(arr, minChar, i + 1);
                lastIndex = findLastIndex(arr, minChar, i + 1, occurrences);
                swap(arr, i, lastIndex);
                return i;
            }
        }
        return lastIndex;
    }

    private static void swapAndPrint(char[] arr, int index) {
        System.out.println(String.valueOf(arr));
    }

    private static void swap(char[] arr, int i, int j) {
        char temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    private static char findMin(char[] arr, int start) {
        char min = arr[start];
        for (int i = start + 1; i < arr.length; i++) {
            if (arr[i] < min) {
                min = arr[i];
            }
        }
        return min;
    }

    private static int countOccurrences(char[] arr, char target, int start) {
        int count = 0;
        for (int i = start; i < arr.length; i++) {
            if (arr[i] == target) {
                count++;
            }
        }
        return count;
    }

    private static int findLastIndex(char[] arr, char target, int start, int occurrences) {
        int index = start;
        for (int j = 0; j < occurrences; j++) {
            index = indexOf(arr, target, index) + 1;
        }
        return index - 1;
    }

    private static int indexOf(char[] arr, char target, int start) {
        for (int i = start; i < arr.length; i++) {
            if (arr[i] == target) {
                return i;
            }
        }
        return -1;
    }
}
